package jjn.round1;

/**
 * @author Jjn
 * @since 2023/4/26 09:48
 */
public class LeetCode8_StringToIntegerAtoi {
    public int myAtoi(String s) {
        if (s == null || s.isBlank()) {
            return 0;
        }
        
        // 去除空格
        s = s.trim();
        
        // 判断正负
        boolean negative = false;
        int i = 0;
        if (s.charAt(0) == '-') {
            negative = true;
            i++;
        } else if (s.charAt(0) == '+') {
            i++;
        }
        
        // 转换数字
        long num = 0;
        for (; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c < '0' || c > '9') {
                break;
            }
            num = num * 10 + (c - '0');
            if (num > Integer.MAX_VALUE) {
                break;
            }
        }
        
        // 处理溢出
        int result;
        if (negative) {
            num = -num;
            if (num < Integer.MIN_VALUE) {
                result = Integer.MIN_VALUE;
            } else {
                result = (int) num;
            }
        } else {
            if (num > Integer.MAX_VALUE) {
                result = Integer.MAX_VALUE;
            } else {
                result = (int) num;
            }
        }
        
        return result;
    }
}
